package com.bjpowernode.web.controller;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.bjpowernode.commons.constants.RedisKey;
import com.fasterxml.jackson.databind.ObjectMapper;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("sms")
@CrossOrigin
public class SMSController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ObjectMapper objectMapper;

    @GetMapping("send")
    public String send(String phone, Integer type) throws Exception {

        // 生成4位随机验证码
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            int num = random.nextInt(10);
            code += num;
        }
        System.out.println("code===="+code);
        // 保存验证码，用于判断验证码是否正确，时效5分钟
        // 参数1是格式化的字符串，第2个参数替换第1个参数中的第1个%s，第3个参数替换第1个参数中的第2个%s...
        String key = null;
        // 该验证码用于登录，默认为注册
        if (type == 1) {
            key = String.format(RedisKey.SMS_LOGIN, phone);
        } else {
            key = String.format(RedisKey.SMS_REG, phone);
        }
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);

//TODO 待修改
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
//                .accessKeyId("LTAI5tAAKx2L62Rnh1LTuV4y")
//                .accessKeySecret("w6jOyHYZ0pQCyDyo7OvOBQNzNUla2q")
                .accessKeyId("LTAI5tKKN1M9FttThBkvUswp")
                .accessKeySecret("qmcamI3a1AZWrH8XJ6qkFycmiNxfc4")
                .build());

        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou")
                .credentialsProvider(provider)
                .overrideConfiguration(
                ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
            .signName("易鹏祥的个人博客")
            .templateCode("SMS_460860336")
            .phoneNumbers(phone)
            .templateParam("{\"code\":\"" + code + "\"}")
            .build();

        client.sendSms(sendSmsRequest);

        client.close();

//TODO 待修改
//        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
//        Client client = createClient("LTAI5tAAKx2L62Rnh1LTuV4y", "w6jOyHYZ0pQCyDyo7OvOBQNzNUla2q");
//        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
//                .signName("阿里云短信测试")
//                .templateCode("SMS_154950909")
//                .phoneNumbers(phone)
//                .templateParam("{\"code\":\"" + code + "\"}")
//                .build();
//        //15098041809
//        SendSmsResponse sendSmsResponse = client.(sendSmsRequest, runtime);
//        SendSmsResponseBody body = sendSmsResponse.getBody();
//        RuntimeOptions runtime = new RuntimeOptions();
//        try {
//            // 复制代码运行请自行打印 API 的返回值
//            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
//            SendSmsResponseBody body = sendSmsResponse.getBody();
//
//            String json = objectMapper.writeValueAsString(body);
//            System.out.println(json);
//
//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//        }
        return code;
    }

    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
//    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
//        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
//                // 必填，您的 AccessKey ID
//                .setAccessKeyId(accessKeyId)
//                // 必填，您的 AccessKey Secret
//                .setAccessKeySecret(accessKeySecret);
//        // 访问的域名
//        config.endpoint = "dysmsapi.aliyuncs.com";
//        return new Client(config);
//    }
}
